package com.jeesite.modules.kj.utils;

import sun.misc.BASE64Encoder;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class ImageUtil {
    private static String strNetImageToBase64;

    public ImageUtil() {
    }

    public static void main(String[] args) {
        String netImagePath = "https://thirdwx.qlogo.cn/mmopen/vi_32/POgEwh4mIHO4nibH0KlMECNjjGxQUq24ZEaGT4poC6icRiccVGKSyXwibcPq4BWmiaIGuG1icwxaQX6grC9VemZoJ8rg/132";
        NetImageToBase64(netImagePath);
    }

    public static byte[] getNetImageByte(String netImagePath){
        URL urlConet = null;
        try {
            urlConet = new URL(netImagePath);
            URLConnection con = urlConet.openConnection();
            InputStream in = con.getInputStream();

            byte[] buffer = new byte[4 * 1024];
            int n = 0;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            byte[] bs = out.toByteArray();

            return bs;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String NetImageToBase64(String netImagePath) {
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        String strNetImageToBase64 = "";

        try {
            URL url = new URL(netImagePath);
            byte[] by = new byte[1024];
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);

            try {
                InputStream is = conn.getInputStream();
                boolean var7 = true;

                int len;
                while((len = is.read(by)) != -1) {
                    data.write(by, 0, len);
                }

                BASE64Encoder encoder = new BASE64Encoder();
                strNetImageToBase64 = encoder.encode(data.toByteArray());
                System.out.println("网络图片转换Base64:" + strNetImageToBase64);
                is.close();
            } catch (IOException var9) {
                var9.printStackTrace();
            }
        } catch (IOException var10) {
            var10.printStackTrace();
        }

        return strNetImageToBase64;
    }
}
